<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <text class="iconfont navbar-icon">&#xe65d;</text>
      </view>
      <text class="navbar-title">{{ isEdit ? '编辑地址' : '新增地址' }}</text>
      <view class="navbar-right" @click="handleSave">
        <text class="save-text" :class="{ disabled: loading }">
          {{ loading ? '保存中...' : '保存' }}
        </text>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 收货人信息 -->
      <view class="form-group">
        <text class="form-label">收货人</text>
        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.receiverName" 
            placeholder="请输入收货人姓名"
            maxlength="20"
            @blur="validateReceiverName"
          />
        </view>
        <text v-if="errors.receiverName" class="error-text">{{ errors.receiverName }}</text>
      </view>

      <!-- 手机号 -->
      <view class="form-group">
        <text class="form-label">手机号</text>
        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.receiverPhone" 
            placeholder="请输入手机号"
            type="number"
            maxlength="11"
            @blur="validateReceiverPhone"
          />
        </view>
        <text v-if="errors.receiverPhone" class="error-text">{{ errors.receiverPhone }}</text>
      </view>

      <!-- 地区选择 -->
      <view class="form-group">
        <text class="form-label">所在地区</text>
        <picker 
          mode="multiSelector" 
          :value="regionIndex"
          :range="regionData"
          range-key="name"
          @change="onRegionChange"
          @columnchange="onRegionColumnChange"
        >
          <view class="form-item form-picker">
            <text class="picker-text" :class="{ placeholder: !regionText }">
              {{ regionText || '请选择省市区' }}
            </text>
            <text class="iconfont picker-arrow">&#xe65f;</text>
          </view>
        </picker>
        <text v-if="errors.region" class="error-text">{{ errors.region }}</text>
      </view>

      <!-- 详细地址 -->
      <view class="form-group">
        <text class="form-label">详细地址</text>
        <view class="form-item">
          <textarea 
            class="form-textarea" 
            v-model="formData.detailAddress" 
            placeholder="请输入详细地址（如街道、楼层、门牌号等）"
            maxlength="200"
            @blur="validateDetailAddress"
          />
        </view>
        <text v-if="errors.detailAddress" class="error-text">{{ errors.detailAddress }}</text>
      </view>

      <!-- 邮政编码 -->
      <view class="form-group">
        <text class="form-label">邮政编码</text>
        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.postalCode" 
            placeholder="请输入邮政编码（可选）"
            type="number"
            maxlength="6"
          />
        </view>
      </view>

      <!-- 地址标签 -->
      <view class="form-group">
        <text class="form-label">地址标签</text>
        <view class="label-options">
          <view 
            v-for="label in labelOptions" 
            :key="label"
            class="label-option"
            :class="{ active: formData.addressLabel === label }"
            @click="selectLabel(label)"
          >
            <text class="label-text">{{ label }}</text>
          </view>
          <view 
            class="label-option custom-label"
            :class="{ active: isCustomLabel }"
            @click="showCustomLabelInput"
          >
            <text class="label-text">自定义</text>
          </view>
        </view>
        <view v-if="showCustomInput" class="custom-input-container">
          <input 
            class="custom-input" 
            v-model="customLabel" 
            placeholder="请输入自定义标签"
            maxlength="10"
            @confirm="confirmCustomLabel"
            @blur="confirmCustomLabel"
          />
        </view>
      </view>

      <!-- 设为默认地址 -->
      <view class="form-group">
        <view class="checkbox-group">
          <label class="checkbox-item">
            <checkbox 
              :checked="formData.isDefault"
              @change="onDefaultChange"
              color="#667eea"
            />
            <text class="checkbox-text">设为默认地址</text>
          </label>
        </view>
      </view>
    </view>

    <!-- 位置信息获取 -->
    <view class="location-section">
      <view class="location-item" @click="getCurrentLocation">
        <text class="location-icon">📍</text>
        <text class="location-text">获取当前位置</text>
        <text class="location-desc">自动填写地址信息</text>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request.js';

export default {
  data() {
    return {
      isEdit: false,
      addressId: null,
      loading: false,
      
      // 表单数据
      formData: {
        receiverName: '',
        receiverPhone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        postalCode: '',
        addressLabel: '',
        isDefault: false,
        longitude: null,
        latitude: null
      },
      
      // 验证错误
      errors: {
        receiverName: '',
        receiverPhone: '',
        region: '',
        detailAddress: ''
      },
      
      // 地区选择相关
      regionData: [[], [], []], // 省市区数据
      regionIndex: [0, 0, 0],
      regionText: '',
      
      // 地址标签
      labelOptions: ['家', '公司', '学校'],
      customLabel: '',
      showCustomInput: false,
      
      // 模拟的省市区数据（实际项目中应该从API获取）
      regionFullData: {
        provinces: [
          { name: '北京市', code: '110000', cities: [
            { name: '北京市', code: '110100', districts: [
              { name: '东城区', code: '110101' },
              { name: '西城区', code: '110102' },
              { name: '朝阳区', code: '110105' },
              { name: '丰台区', code: '110106' },
              { name: '海淀区', code: '110108' }
            ]}
          ]},
          { name: '上海市', code: '310000', cities: [
            { name: '上海市', code: '310100', districts: [
              { name: '黄浦区', code: '310101' },
              { name: '徐汇区', code: '310104' },
              { name: '长宁区', code: '310105' },
              { name: '静安区', code: '310106' },
              { name: '普陀区', code: '310107' }
            ]}
          ]},
          { name: '广东省', code: '440000', cities: [
            { name: '广州市', code: '440100', districts: [
              { name: '荔湾区', code: '440103' },
              { name: '越秀区', code: '440104' },
              { name: '海珠区', code: '440105' },
              { name: '天河区', code: '440106' },
              { name: '白云区', code: '440111' }
            ]},
            { name: '深圳市', code: '440300', districts: [
              { name: '罗湖区', code: '440303' },
              { name: '福田区', code: '440304' },
              { name: '南山区', code: '440305' },
              { name: '宝安区', code: '440306' },
              { name: '龙岗区', code: '440307' }
            ]}
          ]}
        ]
      }
    }
  },
  
  computed: {
    isCustomLabel() {
      return this.formData.addressLabel && !this.labelOptions.includes(this.formData.addressLabel);
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.isEdit = true;
      this.addressId = options.id;
      uni.setNavigationBarTitle({
        title: '编辑地址'
      });
      this.loadAddressData();
    } else {
      uni.setNavigationBarTitle({
        title: '新增地址'
      });
    }
    
    this.initRegionData();
  },
  
  methods: {
    // 初始化地区数据
    initRegionData() {
      const provinces = this.regionFullData.provinces;
      this.regionData[0] = provinces;
      
      if (provinces.length > 0) {
        this.regionData[1] = provinces[0].cities || [];
        if (this.regionData[1].length > 0) {
          this.regionData[2] = this.regionData[1][0].districts || [];
        }
      }
    },
    
    // 加载地址数据
    async loadAddressData() {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        const response = await request({
          url: `/api/address/${this.addressId}`,
          method: 'GET'
        });
        
        console.log('🔍 调试：API响应数据', response);
        
        if (response.code === 200) {
          const data = response.data;
          console.log('🔍 调试：解析的地址数据', data);
          
          this.formData = {
            receiverName: data.receiverName || '',
            receiverPhone: data.receiverPhone || '',
            province: data.province || '',
            city: data.city || '',
            district: data.district || '',
            detailAddress: data.detailAddress || '',
            postalCode: data.postalCode || '',
            addressLabel: data.addressLabel || '',
            isDefault: data.isDefault || false,
            longitude: data.longitude,
            latitude: data.latitude
          };
          
          console.log('🔍 调试：设置后的formData', this.formData);
          
          // 设置地区选择器
          this.setRegionSelector();
          
          console.log('🔍 调试：地区选择器设置后的状态', {
            regionIndex: this.regionIndex,
            regionText: this.regionText
          });
          
        } else {
          console.error('🔍 调试：API返回错误', response);
          uni.showToast({
            title: response.message || '加载地址失败',
            icon: 'error'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        console.error('🔍 调试：加载地址数据异常', error);
        uni.showToast({
          title: '加载地址失败',
          icon: 'error'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } finally {
        uni.hideLoading();
      }
    },
    
    // 设置地区选择器
    setRegionSelector() {
      const { province, city, district } = this.formData;
      
      console.log('🔍 调试：设置地区选择器', { province, city, district });
      console.log('🔍 调试：当前regionData结构', {
        provinces: this.regionData[0]?.length,
        cities: this.regionData[1]?.length,
        districts: this.regionData[2]?.length
      });
      
      if (province && city && district) {
        // 查找对应的索引
        const provinceIndex = this.regionData[0].findIndex(p => p.name === province);
        console.log('🔍 调试：省份匹配', { province, provinceIndex });
        
        if (provinceIndex > -1) {
          this.regionIndex[0] = provinceIndex;
          this.regionData[1] = this.regionData[0][provinceIndex].cities || [];
          
          const cityIndex = this.regionData[1].findIndex(c => c.name === city);
          console.log('🔍 调试：城市匹配', { city, cityIndex });
          
          if (cityIndex > -1) {
            this.regionIndex[1] = cityIndex;
            this.regionData[2] = this.regionData[1][cityIndex].districts || [];
            
            const districtIndex = this.regionData[2].findIndex(d => d.name === district);
            console.log('🔍 调试：区县匹配', { district, districtIndex });
            
            if (districtIndex > -1) {
              this.regionIndex[2] = districtIndex;
            }
          }
        }
        
        this.regionText = `${province} ${city} ${district}`;
        console.log('🔍 调试：最终设置结果', { 
          regionIndex: this.regionIndex,
          regionText: this.regionText 
        });
      } else {
        console.log('🔍 调试：省市区数据不完整，跳过地区选择器设置');
      }
    },
    
    // 地区选择变化
    onRegionChange(e) {
      this.regionIndex = e.detail.value;
      const [provinceIndex, cityIndex, districtIndex] = this.regionIndex;
      
      if (this.regionData[0][provinceIndex] && 
          this.regionData[1][cityIndex] && 
          this.regionData[2][districtIndex]) {
        
        this.formData.province = this.regionData[0][provinceIndex].name;
        this.formData.city = this.regionData[1][cityIndex].name;
        this.formData.district = this.regionData[2][districtIndex].name;
        
        this.regionText = `${this.formData.province} ${this.formData.city} ${this.formData.district}`;
        this.errors.region = '';
      }
    },
    
    // 地区列变化
    onRegionColumnChange(e) {
      const { column, value } = e.detail;
      this.regionIndex[column] = value;
      
      if (column === 0) {
        // 省份变化，更新城市列表
        this.regionData[1] = this.regionData[0][value].cities || [];
        this.regionData[2] = [];
        this.regionIndex[1] = 0;
        this.regionIndex[2] = 0;
        
        if (this.regionData[1].length > 0) {
          this.regionData[2] = this.regionData[1][0].districts || [];
        }
      } else if (column === 1) {
        // 城市变化，更新区县列表
        this.regionData[2] = this.regionData[1][value].districts || [];
        this.regionIndex[2] = 0;
      }
    },
    
    // 选择地址标签
    selectLabel(label) {
      this.formData.addressLabel = label;
      this.showCustomInput = false;
    },
    
    // 显示自定义标签输入
    showCustomLabelInput() {
      this.showCustomInput = true;
      this.customLabel = this.isCustomLabel ? this.formData.addressLabel : '';
    },
    
    // 确认自定义标签
    confirmCustomLabel() {
      if (this.customLabel.trim()) {
        this.formData.addressLabel = this.customLabel.trim();
      }
      this.showCustomInput = false;
    },
    
    // 默认地址选择变化
    onDefaultChange(e) {
      this.formData.isDefault = e.detail.value.length > 0;
    },
    
    // 获取当前位置
    getCurrentLocation() {
      uni.showLoading({
        title: '定位中...'
      });
      
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.formData.longitude = res.longitude;
          this.formData.latitude = res.latitude;
          
          // 这里可以调用逆地理编码API来获取地址信息
          // 为了简化，这里只是显示成功消息
          uni.showToast({
            title: '定位成功',
            icon: 'success'
          });
        },
        fail: (error) => {
          console.error('定位失败:', error);
          uni.showToast({
            title: '定位失败，请手动选择地址',
            icon: 'none'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
    
    // 验证收货人姓名
    validateReceiverName() {
      const name = this.formData.receiverName.trim();
      if (!name) {
        this.errors.receiverName = '请输入收货人姓名';
        return false;
      }
      if (name.length < 2) {
        this.errors.receiverName = '姓名至少2个字符';
        return false;
      }
      this.errors.receiverName = '';
      return true;
    },
    
    // 验证手机号
    validateReceiverPhone() {
      const phone = this.formData.receiverPhone.trim();
      if (!phone) {
        this.errors.receiverPhone = '请输入手机号';
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        this.errors.receiverPhone = '请输入有效的手机号';
        return false;
      }
      this.errors.receiverPhone = '';
      return true;
    },
    
    // 验证详细地址
    validateDetailAddress() {
      const address = this.formData.detailAddress.trim();
      if (!address) {
        this.errors.detailAddress = '请输入详细地址';
        return false;
      }
      if (address.length < 5) {
        this.errors.detailAddress = '详细地址至少5个字符';
        return false;
      }
      this.errors.detailAddress = '';
      return true;
    },
    
    // 验证地区选择
    validateRegion() {
      if (!this.formData.province || !this.formData.city || !this.formData.district) {
        this.errors.region = '请选择省市区';
        return false;
      }
      this.errors.region = '';
      return true;
    },
    
    // 验证所有字段
    validateAllFields() {
      const isNameValid = this.validateReceiverName();
      const isPhoneValid = this.validateReceiverPhone();
      const isRegionValid = this.validateRegion();
      const isAddressValid = this.validateDetailAddress();
      
      return isNameValid && isPhoneValid && isRegionValid && isAddressValid;
    },
    
    // 保存地址
    async handleSave() {
      if (this.loading) return;
      
      if (!this.validateAllFields()) {
        uni.showToast({
          title: '请检查输入信息',
          icon: 'error'
        });
        return;
      }
      
      this.loading = true;
      
      try {
        const requestData = {
          receiverName: this.formData.receiverName.trim(),
          receiverPhone: this.formData.receiverPhone.trim(),
          province: this.formData.province,
          city: this.formData.city,
          district: this.formData.district,
          detailAddress: this.formData.detailAddress.trim(),
          postalCode: this.formData.postalCode.trim() || null,
          addressLabel: this.formData.addressLabel || null,
          isDefault: this.formData.isDefault,
          longitude: this.formData.longitude,
          latitude: this.formData.latitude
        };
        
        let response;
        if (this.isEdit) {
          response = await request({
            url: `/api/address/update/${this.addressId}`,
            method: 'POST',
            data: requestData
          });
        } else {
          response = await request({
            url: '/api/address/add',
            method: 'POST',
            data: requestData
          });
        }
        
        if (response.code === 200) {
          uni.showToast({
            title: this.isEdit ? '更新成功' : '添加成功',
            icon: 'success'
          });
          
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.message || '保存失败',
            icon: 'error'
          });
        }
      } catch (error) {
        console.error('保存地址失败:', error);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'error'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style scoped>
/* 基本样式 */
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

/* 自定义导航栏 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-left {
  width: 60px;
}

.navbar-icon {
  font-size: 20px;
  color: #333;
}

.navbar-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.navbar-right {
  width: 60px;
  text-align: right;
}

.save-text {
  color: #667eea;
  font-size: 16px;
}

.save-text.disabled {
  color: #ccc;
}

/* 表单区域 */
.form-section {
  margin-top: 60px;
  padding: 16px;
}

.form-group {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.form-label {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.form-item {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 12px;
}

.form-input {
  width: 100%;
  font-size: 16px;
  color: #333;
  padding: 8px 0;
}

.form-textarea {
  width: 100%;
  font-size: 16px;
  color: #333;
  padding: 8px 0;
  min-height: 80px;
}

.form-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  cursor: pointer;
}

.picker-text {
  font-size: 16px;
  color: #333;
}

.picker-text.placeholder {
  color: #999;
}

.picker-arrow {
  font-size: 14px;
  color: #ccc;
}

.error-text {
  color: #ff4757;
  font-size: 12px;
  margin-top: 8px;
}

/* 地址标签 */
.label-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.label-option {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background: #fff;
}

.label-option.active {
  background: #667eea;
  border-color: #667eea;
}

.label-text {
  font-size: 14px;
  color: #333;
}

.label-option.active .label-text {
  color: #fff;
}

.custom-input-container {
  margin-top: 12px;
}

.custom-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

/* 复选框 */
.checkbox-group {
  margin-top: 8px;
}

.checkbox-item {
  display: flex;
  align-items: center;
}

.checkbox-text {
  margin-left: 8px;
  font-size: 16px;
  color: #333;
}

/* 位置信息 */
.location-section {
  padding: 0 16px 20px;
}

.location-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.location-item:active {
  background: #f8f8f8;
}

.location-icon {
  font-size: 20px;
  margin-right: 12px;
}

.location-text {
  font-size: 16px;
  color: #333;
  margin-right: 8px;
}

.location-desc {
  font-size: 12px;
  color: #999;
}
</style>